import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { Request } from 'express'
import config from 'src/config'
import AesUtils from 'src/utils/aes'
import { IRequest } from 'src/interface/common'

interface Response<T> {
	data: T
}

@Injectable()
export class AppResponseInterceptor<T> implements NestInterceptor<T, Response<T>> {
	constructor() { }
	intercept(context: ExecutionContext, next: CallHandler<T>): Observable<any> {
		const request = context.switchToHttp().getRequest<IRequest>()
		let excludePath=[]

		if (request.path.startsWith("/app")&&!excludePath.includes(request.path)) {

			let encry = (data) => {
				// if (config.env == "dev"||config.env=="pre"||config.env=="test"||config.env=="prod") {
				// 	if (request.headers["api-secret"] == "1") {
				// 		data = AesUtils.encryptAes(data)
				// 	}
				// } else {
				// 	data = AesUtils.encryptAes(data)
				// }
				let time=Date.now()-request.requestTime
				Logger.log(request.url, `正常接口请求--来自客户端,耗时：${time}ms`)
				return {
					data: data,
					code: 0,
					message: '请求成功'
				}
			}

			return next.handle().pipe(
				map(async data => {
					if (!request.path.startsWith('/app') && !request.path.startsWith('/admin')) {
						return data
					} else {
						return encry(data)
					}

				})
			)
		}
		return next.handle()
	}
}
